package com.jboltai.pptextract;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Main class for the PPT Extract application
 */
public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        if (args.length < 2) {
            printUsage();
            System.exit(1);
        }

        String command = args[0].toLowerCase();
        String inputFilePath = args[1];
        File inputFile = new File(inputFilePath);

        if (!inputFile.exists() || !inputFile.isFile()) {
            logger.error("Input file does not exist or is not a file: {}", inputFilePath);
            System.exit(1);
        }

        PPTProcessor processor = new PPTProcessorImpl();

        try {
            switch (command) {
                case "pdf":
                    convertToPdf(processor, inputFile, args);
                    break;
                case "text":
                    extractText(processor, inputFile, args);
                    break;
                case "markdown":
                    convertToMarkdown(processor, inputFile, args);
                    break;
                case "media":
                    extractMedia(processor, inputFile, args);
                    break;
                case "full":
                    extractFullContent(processor, inputFile, args);
                    break;
                default:
                    logger.error("Unknown command: {}", command);
                    printUsage();
                    System.exit(1);
            }
        } catch (Exception e) {
            logger.error("Error processing file: {}", e.getMessage(), e);
            System.exit(1);
        }
    }

    private static void convertToPdf(PPTProcessor processor, File inputFile, String[] args) throws IOException {
        File outputFile;
        if (args.length > 2) {
            outputFile = new File(args[2]);
        } else {
            String outputPath = removeExtension(inputFile.getPath()) + ".pdf";
            outputFile = new File(outputPath);
        }

        logger.info("Converting {} to PDF: {}", inputFile.getName(), outputFile.getPath());
        processor.convertToPdf(inputFile, outputFile);
        logger.info("Conversion complete: {}", outputFile.getPath());
    }

    private static void extractText(PPTProcessor processor, File inputFile, String[] args) throws IOException {
        String text = processor.extractText(inputFile);
        
        if (args.length > 2) {
            File outputFile = new File(args[2]);
            Files.writeString(outputFile.toPath(), text);
            logger.info("Text extracted to: {}", outputFile.getPath());
        } else {
            System.out.println("Extracted Text:");
            System.out.println("==============");
            System.out.println(text);
        }
    }

    private static void convertToMarkdown(PPTProcessor processor, File inputFile, String[] args) throws IOException {
        File outputFile;
        if (args.length > 2) {
            outputFile = new File(args[2]);
        } else {
            String outputPath = removeExtension(inputFile.getPath()) + ".md";
            outputFile = new File(outputPath);
        }

        logger.info("Converting {} to Markdown: {}", inputFile.getName(), outputFile.getPath());
        processor.convertToMarkdown(inputFile, outputFile);
        logger.info("Conversion complete: {}", outputFile.getPath());
    }
    
    private static void extractMedia(PPTProcessor processor, File inputFile, String[] args) throws IOException {
        File outputDir;
        if (args.length > 2) {
            outputDir = new File(args[2]);
        } else {
            outputDir = new File(removeExtension(inputFile.getPath()) + "_media");
        }

        logger.info("Extracting media from {} to directory: {}", inputFile.getName(), outputDir.getPath());
        int count = processor.extractMedia(inputFile, outputDir);
        logger.info("Extracted {} media files", count);
    }
    
    private static void extractFullContent(PPTProcessor processor, File inputFile, String[] args) throws IOException {
        File outputDir;
        if (args.length > 2) {
            outputDir = new File(args[2]);
        } else {
            outputDir = new File(removeExtension(inputFile.getPath()) + "_content");
        }

        logger.info("Extracting full content from {} to directory: {}", inputFile.getName(), outputDir.getPath());
        processor.extractFullContent(inputFile, outputDir);
        logger.info("Full content extraction complete. Report available at: {}", 
                new File(outputDir, "extraction_report.html").getPath());
    }

    private static String removeExtension(String filePath) {
        int lastDot = filePath.lastIndexOf('.');
        if (lastDot > 0) {
            return filePath.substring(0, lastDot);
        }
        return filePath;
    }

    private static void printUsage() {
        System.out.println("Usage: java -jar jboltai_ppt_extract.jar <command> <input-file> [output-file/dir]");
        System.out.println("Commands:");
        System.out.println("  pdf       - Convert PPT to PDF");
        System.out.println("  text      - Extract text from ppt");
        System.out.println("  markdown  - Convert PPT to Markdown");
        System.out.println("  media     - Extract media files (images, videos, audio) from ppt");
        System.out.println("  full      - Extract both text and media with a comprehensive report");
        System.out.println("Examples:");
        System.out.println("  java -jar jboltai_ppt_extract.jar pdf presentation.pptx output.pdf");
        System.out.println("  java -jar jboltai_ppt_extract.jar text presentation.pptx output.txt");
        System.out.println("  java -jar jboltai_ppt_extract.jar markdown presentation.pptx output.md");
        System.out.println("  java -jar jboltai_ppt_extract.jar media presentation.pptx media_folder");
        System.out.println("  java -jar jboltai_ppt_extract.jar full presentation.pptx content_folder");
    }
} 
